package org.spider.core.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.domain.vo.FileVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class FileService {

    @Value("${spider.fileDir}")
    private String fileDir;

    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final Logger logger = LoggerFactory.getLogger(FileService.class);
    public List<FileVo> list(){
        File file=new File(fileDir);
        File[] files = file.listFiles();
        List<FileVo> fileVos=new ArrayList<>();
        if (files != null) {
            Arrays.sort(files,(f1,f2)->Long.compare(f2.lastModified(),f1.lastModified())); //降序排序
            for(File f:files){
                FileVo fileVo = FileVo.builder()
                        .filename(f.getName())
                        .createTime(sdf.format(new Date(f.lastModified())))
                        .length(f.length() / 1024)
                        .path(file.getPath())
                        .build();
                fileVos.add(fileVo);
            }
        }

        return fileVos;
    }

    public void download(String filename, OutputStream os){
        File file=new File(fileDir,filename);
        try(FileInputStream in=new FileInputStream(file)){
            FileCopyUtils.copy(in,os);
            os.flush();
        }catch (Exception e){
            logger.info("download file error"+e.getMessage());
        }
    }

    public boolean deleteFile(String filename){
        File file=new File(fileDir,filename);
        return file.delete();
    }

}
